<?php

namespace common\models;

use Yii;
use yii\base\Model;
use yii\captcha\Captcha;

/**
 * Login form
 */
class LoginForm extends Model {

    public $username;
    public $password_hash;
    public $verifyCode;
    public $rememberMe;
    private $_user;

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            // username and password_hash are both required
            [['username', 'password_hash', 'verifyCode'], 'required', 'message' => '{attribute}不能为空.'], [['username'], 'string', 'tooLong' => '用户名不能为空'],
            // rememberMe must be a boolean value
//            ['rememberMe', 'boolean'],
            // password_hash is validated by validatePassword()
            ['password_hash', 'validatePassword'],
//            ['code', 'validateCode'],
            ['username', 'validateUsername'],
            ['verifyCode', 'captcha', 'message'=>'验证码错误'],

        ];
    }

    public function attributeLabels() {
        return [
            'username' => '用户名',
            'password_hash' => '密码',
            'verifyCode' => '验证码',
            'rememberMe' => '记住我',
        ];
    }

    /**
     * Validates the password_hash.
     * This method serves as the inline validation for password_hash.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validatePassword($attribute, $params) {
        if (!$this->hasErrors()) {
            $user = $this->getUser();
            if (!$user || !$user->validatePassword($this->password_hash)) {
                $this->addError($attribute, '密码错误，请重新输入');
            }
        }
    }

    /**
     * Logs in a user using the provided username and password_hash.
     *
     * @return bool whether the user is logged in successfully
     */
    public function login() {
        if ($this->validate()) {
            return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
        } else {
            return false;
        }
    }

    /**
     * Finds user by [[username]]
     *
     * @return User|null
     */
    protected function getUser() {
        if ($this->_user === null) {
            $this->_user = User::findByUsername($this->username);
        }

        return $this->_user;
    }

    public function validateUsername($attribute, $params) {
        if (!$this->hasErrors()) {
            $user = $this->getUser();
            if (!$user) {
                $this->addError($attribute, '该账号不存在.');
            }
        }
    }

}
